package com.zw.knowlege.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Sets;
import com.zw.common.constant.ExperienceStatusEnum;
import com.zw.common.constant.NumberConst;
import com.zw.common.response.ResponseCode;
import com.zw.common.response.ResponseResult;
import com.zw.knowlege.common.StaticValue;
import com.zw.knowlege.mapper.CollectRecordMapper;
import com.zw.knowlege.mapper.ExperienceBaseMapper;
import com.zw.knowlege.pojo.ExperiencePojo;
import com.zw.knowlege.service.ExperienceBaseService;
import com.zw.knowlege.service.ParamParseService;
import com.zw.knowlege.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

@Slf4j
@Service
public class ExperienceBaseServiceImpl implements ExperienceBaseService{

    @Autowired
    private ExperienceBaseMapper experienceBaseMapper;

    @Autowired
    private ParamParseService paramParseService;

    @Autowired
    private CollectRecordMapper collectRecordMapper;

    @Override
    public ResponseResult insertExperienceBase(JSONObject paramJson, ExperiencePojo experiencePojo) {
        experiencePojo = (null == experiencePojo) ? (ExperiencePojo)paramParseService.parseParam(paramJson, ExperiencePojo.class, null) : experiencePojo;
        if(null == experiencePojo){
            log.info("将【{}】经验入库出现异常，请排查", paramJson);
            return ResponseResult.failure("【"+paramJson+"】经验信息新建出现异常");
        }
        log.info("开始将ID【{}】的经验记录插入到表中", experiencePojo.getExperienceid());
        int insertFlag = experienceBaseMapper.insertExperienceBase(experiencePojo);
        if(insertFlag > NumberConst.NUM_0){
            log.info("导入ID【{}】的记录成功", experiencePojo.getExperienceid());
            return new ResponseResult(ResponseCode.SUCCESS, "ID【"+ experiencePojo.getExperienceid() +"】的记录导入成功");
        }else{
            log.warn("导入ID【{}】的记录失败", experiencePojo.getExperienceid());
            return new ResponseResult(ResponseCode.FAILURE, "ID【"+ experiencePojo.getExperienceid() +"】的记录导入失败");
        }
    }

    @Override
    public boolean isRelease(String experienceId) {
        return experienceBaseMapper.queryReleaseStatus(experienceId) > 0;
    }

    /**
     * 编辑经验
     * @param experiencePojo
     * @return
     */
    @Override
    public ResponseResult exitExperienceBase(JSONObject paramJson) {
        ExperiencePojo experiencePojo = (ExperiencePojo)paramParseService.parseParam(paramJson, ExperiencePojo.class, null);
        if(null == experiencePojo){
            log.info("编辑【{}】经验出现异常，请排查", paramJson);
            return ResponseResult.failure("编辑【"+paramJson+"】经验出现异常");
        }
        log.info("开始编辑ID【{}】的经验记录", experiencePojo.getExperienceid());
        // 首先判断是否发布过
        if(isRelease(experiencePojo.getExperienceid())){
            // 发布过，则需要更新ID、历史ID和创建时间
            experiencePojo.setHistoryid()
                          .setExperienceid(StaticValue.NULL)
                          .setCreatetime(new Timestamp(System.currentTimeMillis()));
            // 此次选择发布，则将历史的改为下线状态且时间更新为最新的
            if(1 == experiencePojo.getStatus()){
                experienceBaseMapper.updateExperienceStatus(ExperienceStatusEnum.OFFINE.getStatus(), new Timestamp(System.currentTimeMillis()) ,experiencePojo.getHistoryid());
            }
            // 更新版本号
            experiencePojo.setVersion(experienceBaseMapper.getExperienceVersion(experiencePojo.getHistoryid()) + 1);
            return insertExperienceBase(paramJson, experiencePojo);
        }else{
            // 未发布过
            experiencePojo.setUpdatetime(new Timestamp(System.currentTimeMillis()));
            experienceBaseMapper.updateExperienceBase(experiencePojo);
            return new ResponseResult(ResponseCode.SUCCESS);
        }
    }

    @Override
    public PageInfo<ExperiencePojo> homepageQueryExperience(JSONObject paramJson) {
        Map<String, Object> paramMap;
        if(CommonUtils.nullOrEmpty(paramJson.toJSONString())){
            paramMap = new HashMap<>();
            paramMap.put(StaticValue.PAGENUM, 1);
            paramMap.put(StaticValue.PAGESIZE, 10);
        }else{
            paramMap = (Map<String, Object>)paramParseService.parseParam(paramJson, Map.class,
                    new String[]{StaticValue.KEYWORD, StaticValue.EXPERIENCE_DEPTTYPE, StaticValue.EXPERIENCE_CLASSINFO,
                            StaticValue.STATUS, StaticValue.EXPERIENCE_USERINFO_USERID, StaticValue.PAGENUM, StaticValue.PAGESIZE});
        }
        log.info("开始查询【经验册首页】");
        PageHelper.startPage(Integer.parseInt(paramMap.getOrDefault(StaticValue.PAGENUM, "1").toString()), Integer.parseInt(paramMap.getOrDefault(StaticValue.PAGESIZE, "10").toString()));
        List<ExperiencePojo> experiencePojoList = experienceBaseMapper.queryExperienceHomePage(paramMap);
        log.info("查询【经验册首页】成功，查询到的总数【{}】", experiencePojoList.size());
        if (CollectionUtil.isNotEmpty(experiencePojoList)) {
            return new PageInfo<>(experiencePojoList);
        } else {
            return new PageInfo<>();
        }
    }

    @Override
    public PageInfo<ExperiencePojo> queryMyExperience(JSONObject paramJson) {
        Map<String, Object> paramMap;
        if(CommonUtils.nullOrEmpty(paramJson.toJSONString())){
            paramMap = new HashMap<>();
            paramMap.put(StaticValue.PAGENUM, 1);
            paramMap.put(StaticValue.PAGESIZE, 10);
        }else{
            paramMap = (Map<String, Object>)paramParseService.parseParam(paramJson, Map.class,
                    new String[]{StaticValue.KEYWORD, StaticValue.EXPERIENCE_DEPTTYPE, StaticValue.EXPERIENCE_CLASSINFO,
                            StaticValue.STATUS, StaticValue.EXPERIENCE_USERINFO_USERID, StaticValue.PAGENUM, StaticValue.PAGESIZE});
        }
        log.info("开始查询【经验册-我的经验】");
        PageHelper.startPage(Integer.parseInt(paramMap.get(StaticValue.PAGENUM).toString()), Integer.parseInt(paramMap.get(StaticValue.PAGESIZE).toString()));
        List<ExperiencePojo> experiencePojoList = experienceBaseMapper.queryNewVersionExperience(paramMap);
        log.info("查询【经验册-我的经验】成功，查询到的总数【{}】", experiencePojoList.size());
        if (CollectionUtil.isNotEmpty(experiencePojoList)) {
            return new PageInfo<>(experiencePojoList);
        } else {
            return new PageInfo<>();
        }
    }

    @Override
    public ExperiencePojo queryExperienceDetails(JSONObject paramJson) {
        Map<String, Object> paramMap = (Map<String, Object>)paramParseService.parseParam(paramJson, Map.class, new String[]{StaticValue.EXPERIENCE_ID, StaticValue.EXPERIENCE_USERINFO_USERID});
        String experienceId = paramMap.get(StaticValue.EXPERIENCE_ID).toString();
        log.info("经验详情Step1-开始查询ID【{}】的详情", experienceId);
        ExperiencePojo experiencePojo = experienceBaseMapper.queryExperienceDetails(experienceId);
        log.info("经验详情Step2-开始查询ID【{}】的相关历史版本", experienceId);
        List<Map<String, Object>> experienceVersionList = experienceBaseMapper.queryExperienceVersionList(experienceId);
        log.info("ID【{}】相关历史版本数【{}】", experienceId, experienceVersionList.size());
        experienceVersionList.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                long time1 = ((Timestamp)o1.get("createtime")).getTime();
                long time2 = ((Timestamp)o2.get("createtime")).getTime();
                return (time1 > time2) ? -1 : ((time1 == time2) ? 0 : 1);
            }
        });
        experiencePojo.setVersionList(experienceVersionList);
        log.info("经验详情Step3-开始查询该用户是否收藏本经验");
        int collectNum = collectRecordMapper.isCollect(paramMap.get(StaticValue.EXPERIENCE_USERINFO_USERID).toString(), experienceId);
        if(collectNum > NumberConst.NUM_0){
            experiencePojo.setCollect(true);
        }
        return experiencePojo;
    }

    @Override
    public ResponseResult updateExperienceStatus(JSONObject paramJson) {
        Map<String, Object> paramMap = (Map<String, Object>)paramParseService.parseParam(paramJson, Map.class, new String[]{StaticValue.EXPERIENCE_ID, StaticValue.EXPERIENCE_ACTION});
        if(null == paramMap){
            log.info("更新【{}】经验状态出现异常，请排查", paramJson);
            return ResponseResult.failure("更新【"+paramJson+"】经验状态出现异常");
        }
        log.info("开始更新ID【{}】的状态为【{}】",paramMap.get(StaticValue.EXPERIENCE_ID),paramMap.get(StaticValue.EXPERIENCE_ACTION));
        ResponseResult responseResult = null;
        try{
            String action = paramMap.get(StaticValue.EXPERIENCE_ACTION).toString();
            if(!ExperienceStatusEnum.RELEASED.getAction().equals(action) && !ExperienceStatusEnum.OFFINE.getAction().equals(action)){
                responseResult = ResponseResult.failure("传如的action值有误，请从RELEASE(发布)和OFFINE(下线)中选择一个，暂时不支持别的");
            }
            experienceBaseMapper.updateExperienceStatus(
                    ExperienceStatusEnum.RELEASED.getAction().equals(action) ? ExperienceStatusEnum.RELEASED.getStatus() : ExperienceStatusEnum.OFFINE.getStatus(),
                    new Timestamp(System.currentTimeMillis()),
                    paramMap.get(StaticValue.EXPERIENCE_ID).toString());
            responseResult = ResponseResult.success("更新ID【"+paramMap.get(StaticValue.EXPERIENCE_ID)+"】状态成功");
        }catch (Exception e){
            log.error("更新任务ID【{}】的状态出现异常【{}】", paramMap.get(StaticValue.EXPERIENCE_ID), e.getCause().toString());
            responseResult = ResponseResult.success("更新ID【"+paramMap.get(StaticValue.EXPERIENCE_ID)+"】状态过程存在异常【"+e.getCause().toString()+"】");
        }
        return responseResult;
    }

    @Override
    public Map<String, Object> querySelectDict(String userid) {
        Map<String, Object> dictMap = new HashMap<>();
        List<ExperiencePojo> experiencePojoList = experienceBaseMapper.querySelectDict(userid);
        if(!experiencePojoList.isEmpty()){
            Set<String> depttypeSet = Sets.newHashSet();
            Set<String> classinfoSet = Sets.newHashSet();
            Set<Map<String, String>> userinfoMapSet = new HashSet<>();
            Set<Map<Integer, String>> statusMapSet = new HashSet<>();
            experiencePojoList.stream().forEach(experiencePojo -> {
                depttypeSet.addAll(Sets.newHashSet(experiencePojo.getDepttype()));
                classinfoSet.addAll(Sets.newHashSet(experiencePojo.getClassinfo()));
                Map<String, String> userinfoMap = new HashMap<>();
                userinfoMap.put(experiencePojo.getUserid(), experiencePojo.getUsername());
                userinfoMapSet.add(userinfoMap);
                Map<Integer, String> statusMap = new HashMap<>();
                if(ExperienceStatusEnum.UPDATED.getStatus().equals(experiencePojo.getStatus())){
                    statusMap.put(experiencePojo.getStatus(), ExperienceStatusEnum.UPDATED.getDesc());
                }
                if(ExperienceStatusEnum.RELEASED.getStatus().equals(experiencePojo.getStatus())){
                    statusMap.put(experiencePojo.getStatus(), ExperienceStatusEnum.RELEASED.getDesc());
                }
                if(ExperienceStatusEnum.OFFINE.getStatus().equals(experiencePojo.getStatus())){
                    statusMap.put(experiencePojo.getStatus(), ExperienceStatusEnum.OFFINE.getDesc());
                }
                statusMapSet.add(statusMap);
            });
            dictMap.put(StaticValue.EXPERIENCE_DEPTTYPE, depttypeSet);
            dictMap.put(StaticValue.EXPERIENCE_CLASSINFO, classinfoSet);
            dictMap.put(StaticValue.EXPERIENCE_USERINFO, userinfoMapSet);
            dictMap.put(StaticValue.STATUS, statusMapSet);
        }
        return dictMap;
    }



}
